<?php
/**
 * Created by PhpStorm.
 * User: ZhangTianyi
 * Date: 2018/3/8
 * Time: 10:51
 */
function alert($str = '')
{
    echo "<script>alert('{$str}')</script>";
}
function upload()
{
    $upload = new \Think\Upload();// 实例化上传类
    $upload->maxSize   =     0 ;// 设置附件上传大小
    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
    $upload->rootPath  =      './'; // 设置附件上传目录    // 上传文件
    $upload->savePath  =      'Public/Uploads/'; // 设置附件上传目录    // 上传文件
    $info   =   $upload->upload();

    if(!$info) {// 上传错误提示错误信息
        echo ($upload->getError());
        return false;
    }else{
        return $info;
    }
}

function shuaxin()
{
    $url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=wxfb1ce4b51d8704f0&grant_type=refresh_token&refresh_token='.$_SESSION['vxaccess']['refresh_token'];
    $res = curl($url);
    if ($res->errcode)
    {
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxfb1ce4b51d8704f0&redirect_uri='.urlencode('http://www.sh229.net/index.php/home/login/login').'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        header('location:'.$url);
        return;
    }
    $_SESSION['vxaccess']['token'] = $res->access_token;
    $_SESSION['vxaccess']['refresh_token'] = $res->refresh_token;
    $_SESSION['vxaccess']['time'] = time() + 7200;
}
function access_token($code = '')
{
    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxfb1ce4b51d8704f0&secret=32a977f10e688f62b69768f791dbf024&code='.$code.'&grant_type=authorization_code';
    $res = curl($url);
    if ($res->errcode) return false;
    $_SESSION['vxaccess']['token'] = $res->access_token;
    $_SESSION['vxaccess']['openid'] = $res->openid;
    $_SESSION['vxaccess']['refresh_token'] = $res->refresh_token;
    $_SESSION['vxaccess']['time'] = time() + 7200;
    $access_token = $res->access_token;
    if ($access_token)
    {
        file_put_contents('./Public/access_token.txt',$access_token.'//'.(time()+7200));
        $res = get_user_info($res);
        var_dump($res);
        return $res;
    }else{
        return 'shibaile';
    }
}
function get_user_info($res)
{
    $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$res->access_token.'&openid='.$res->openid.'&lang=zh_CN';
    $info = curl($url);
    var_dump($info);
    return($info);
}
function curl($url,$post_data = '')
{
    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
    curl_setopt($ch,CURLOPT_HEADER,0);
    //get数据
    if($post_data)
    {
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    }else{
        curl_setopt($ch, CURLOPT_HEADER, 0);
    }
    $output = curl_exec($ch);
    curl_close($ch);
    return(json_decode($output));
}
